package com.uroad.lib.util.check;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;


import com.uroad.lib.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/14 0014.
 */

public class CheckPermissionUtil implements ActivityCompat.OnRequestPermissionsResultCallback{

    /*
    * 例:
    * Manifest.permission.ACCESS_COARSE_LOCATION,
    * Manifest.permission.ACCESS_FINE_LOCATION,
    * Manifest.permission.WRITE_EXTERNAL_STORAGE,
    * Manifest.permission.READ_EXTERNAL_STORAGE,
    * Manifest.permission.READ_PHONE_STATE
    * */
    private String[] needPermissions = {};  //  需要检测的权限列表
    private Activity activity;
    private static final int PERMISSON_REQUESTCODE = 0;
    CheckPermissionCallBack checkPermissionCallBack;

    public CheckPermissionUtil(Activity activity, String[] needPermissions, CheckPermissionCallBack checkPermissionCallBack){
        this.activity = activity;
        this.needPermissions = needPermissions;
        this.checkPermissionCallBack = checkPermissionCallBack;
    }

    public void checkPermissions() {
        List<String> needRequestPermissonList = findDeniedPermissions(needPermissions);
        if (null != needRequestPermissonList
                && needRequestPermissonList.size() > 0) {
            ActivityCompat.requestPermissions(activity,
                    needRequestPermissonList.toArray(
                            new String[needRequestPermissonList.size()]),
                    PERMISSON_REQUESTCODE);
        } else {
            //已经有权限了
            checkPermissionCallBack.permissionAllow();
        }
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        for (String perm : permissions) {
            if (ContextCompat.checkSelfPermission(activity,
                    perm) != PackageManager.PERMISSION_GRANTED || ActivityCompat.shouldShowRequestPermissionRationale(
                    activity, perm)) {
                needRequestPermissonList.add(perm);
            }
        }
        return needRequestPermissonList;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(grantResults)) {
                showMissingPermissionDialog();
            }else{
                //已经添加了权限
                checkPermissionCallBack.permissionAllow();
            }
        }
    }

    /**
     * 显示提示信息
     *
     * @since 2.5.0
     */
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle(R.string.notifyTitle);
        builder.setMessage(R.string.notifyMsg);
        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        checkPermissionCallBack.permissionRefuse();
                    }
                });
        builder.setPositiveButton(R.string.setting,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });
        builder.setCancelable(false);
        builder.show();
    }

    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + activity.getPackageName()));
        activity.startActivity(intent);
    }

    /**
     * 检测是否说有的权限都已经授权
     *
     * @param grantResults
     * @return
     * @since 2.5.0
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }


    public interface CheckPermissionCallBack{
        void permissionAllow();//同意权限
        void permissionRefuse();//拒绝权限（在弹出对话框要求去设置里面设置时候点了取消的回调，而不是禁止的回调）
    }
}
